package com.cr.admin.base.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.cr.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务类
 */
@Service
@Slf4j
public class CaptchaService {

    private static final String CAPTCHA_CACHE_KEY = "captcha:";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 生成验证码
     * @return 验证码key+验证码图片base64
     */
    public Map<String,Object> generateCaptcha(){
        //创建一个gif类型的验证码对象
        //闪屏验证码
        //GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(100, 40);
        //线型验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
        //缓存验证码字符串到redis中
        String key = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(CAPTCHA_CACHE_KEY+key,lineCaptcha.getCode(),2, TimeUnit.MINUTES);
        //封装返回结果map对象并返回
        Map<String,Object> map = new HashMap<>();
        map.put("captchaKey",key);
        map.put("captchaBase64",lineCaptcha.getImageBase64Data());
        return map;
    }

    /**
     * 检查验证码
     * @param captchaKey
     * @param captcha
     */
    public void checkCaptcha(String captchaKey,String captcha){
        //根据key从redis缓存中获取的验证码字符串
        Object value = redisTemplate.opsForValue().get(CAPTCHA_CACHE_KEY+captchaKey);
        //
        redisTemplate.delete(CAPTCHA_CACHE_KEY+captchaKey);
        //判断从redis缓存中获取出来的验证码是否为空(为空说明过期了)
        if (Objects.isNull(value)){
            throw new ServiceException("验证码已过期");
        }
        //判断缓存的验证码和用户输入的验证码是否匹配
        if(!value.toString().equalsIgnoreCase(captcha)){
            throw new ServiceException("验证码不正确");
        }
    }
}
